package com.wmlive.hhvideo.heihei.websocket;

import android.os.Message;

import com.alibaba.fastjson.JSONObject;
import com.wmlive.hhvideo.utils.KLog;

import cn.wmlive.hhvideo.rxbuslib.RxBus2;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;


/**
 * 自定义websocketListener
 * Created by kangzhen on 2017/7/5.
 */

public class MyWebsocketListener extends WebSocketListener {
    public static final String TAG = "websock_service";
    public static final String MSG = "MyWebsocketListener";


    private WebSocket _WebSocket = null;//当前的websocket 对象
    private JSONObject _JsonObject = null;//接受到的服务端的数据

    //回调用的handler 信息
    private MyWebsocketService.ServiceHandler mServiceHandler;


    public MyWebsocketListener() {
        super();
    }

    public MyWebsocketListener(MyWebsocketService.ServiceHandler handler) {
        super();
        mServiceHandler = handler;
    }

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        //与服务器连接成功
        KLog.e(TAG, MSG + "--------onOpen------------");
        _WebSocket = webSocket;
        if (mServiceHandler != null) {
            //通知websocket　连接成功
            mServiceHandler.sendEmptyMessage(MyWebsocketService.STATE_CONNECTED);
        }
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        //收到text 信息
        KLog.e(TAG, MSG + "--------onMessage-----String---:" + text);
        if (mServiceHandler != null) {
            Message msg = mServiceHandler.obtainMessage();
            msg.what = MyWebsocketService.STATE_ONMESSAGE;
            msg.obj = text;
            mServiceHandler.sendMessage(msg);
        } else {
            //发送重新连接
            RxBus2.get().send(MyWebsocketService.STATE_RECONNECTION);
        }
    }

    @Override
    public void onMessage(WebSocket webSocket, ByteString bytes) {
        //收到byteString 信息
        KLog.e(TAG, MSG + "--------onMessage-----ByteString---:" + bytes.toString());
    }

    @Override
    public void onClosing(WebSocket webSocket, int code, String reason) {
        //当没有更多数据传递时，调用
        KLog.e(TAG, MSG + "--------onClosing-----code---:" + code);
        try {
            if (_WebSocket != null) {
                _WebSocket.close(code, null);
            }
        }catch (Exception e) {
            KLog.e(TAG, MSG + "--------onClosing-----Exception---:" + e.getMessage());
        }

    }

    @Override
    public void onClosed(WebSocket webSocket, int code, String reason) {
        //关闭连接
        KLog.e(TAG, MSG + "--------onClosed-----code---:" + code);
        try{
            switch (code){
                case MyWebsocketService.CODE_CLOSE:
                    //用户主动关闭
                    break;
                case MyWebsocketService.CODE_SERVER_CLOSE:
                    //服务
                    onSendReConnection();//发送重连
                    break;
                case MyWebsocketService.CODE_TOKEN_CLOSE:
                    //token失效
                    onSendTokenReConnection();//发送重连
                    break;
            }
        }catch (Exception e){

        }
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        KLog.e(TAG, MSG + "-------------onFailure-------" );
        webSocket.close(MyWebsocketService.CODE_CLOSE, null);
        //发送重新连接
        onSendReConnection();
    }
    //token 失效的重新
    private void onSendTokenReConnection() {
        if (mServiceHandler != null) {
            Message msg =mServiceHandler.obtainMessage();
            msg.what=MyWebsocketService.STATE_TOKEN_RECONNECTION;
            mServiceHandler.sendMessageDelayed(msg,2000);
        } else {
            RxBus2.get().send(MyWebsocketService.STATE_TOKEN_RECONNECTION);
        }
    }
    //发送重新连接命令
    private void onSendReConnection() {
        if (mServiceHandler != null) {
            mServiceHandler.sendEmptyMessage(MyWebsocketService.STATE_RECONNECTION);
        } else {
            RxBus2.get().send(MyWebsocketService.STATE_RECONNECTION);
        }
    }

    //关闭websocke 主动，并且断开连接
    public void onClosedWebsocket() {
        if (_WebSocket != null) {
            _WebSocket.close(MyWebsocketService.CODE_CLOSE, null);
        }
        mServiceHandler = null;
    }
}
